package com.gzucm.Scholarship.service;

import com.gzucm.Scholarship.common.ConstValues;
import com.gzucm.Scholarship.common.base.BaseServiceImpl;
import com.gzucm.Scholarship.common.enums.ItemState;
import com.gzucm.Scholarship.common.enums.ScoreType;
import com.gzucm.Scholarship.common.enums.UserType;
import com.gzucm.Scholarship.dao.BonusItemDao;
import com.gzucm.Scholarship.dao.StudentDao;
import com.gzucm.Scholarship.dto.ResultDTO;
import com.gzucm.Scholarship.entity.BonusItem;
import com.gzucm.Scholarship.entity.Student;
import com.gzucm.Scholarship.entity.UserInfo;
import com.gzucm.Scholarship.exception.ImportException;
import com.gzucm.Scholarship.util.LogUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class StudentService extends BaseServiceImpl<Student> {

    private StudentDao studentDao;

    private BonusItemDao bonusItemDao;

    private CurrentService currentService;

    private SystemService systemService;

    private FileService fileService;

    public StudentService(StudentDao dao, BonusItemDao bonusItemDao, CurrentService currentService, SystemService systemService, FileService fileService) {
        super(dao);
        this.studentDao = dao;
        this.bonusItemDao = bonusItemDao;
        this.currentService = currentService;
        this.systemService = systemService;
        this.fileService = fileService;
    }

    public List<Student> findByNumberStartsWith(String year) {
        return studentDao.findByNumberStartsWith(year);
    }

    public Student findByIdCard(String idCard) {
        return studentDao.findByIdCard(idCard);
    }

    public Student findByNumber(String number) {
        return studentDao.findByNumber(number);
    }

    public ResultDTO addBonusItem(BonusItem item) {
        if (!systemService.getState().getData().getOpen()) {
            return ResultDTO.failure(HttpStatus.FORBIDDEN, "系统当前不能填报");
        }

        ScoreType scoreType = ScoreType.get(item.getType());
        if (Objects.isNull(item.getJob()) || !Objects.equals(ScoreType.DY, scoreType)) {//只有德育有分职位和非职位
            item.setJob(false);
        }
        item.setState(ItemState.SAVED.getCode());
        item.setApplicant(currentService.getCurrentUser().getId());
        item.setDeleteflag(false);
        item.setFile(null);
        item.setId(null);
        return ResultDTO.success("保存成功", bonusItemDao.save(item));
    }

    public ResultDTO deleteBonusItemById(String id) {
        if (!systemService.getState().getData().getOpen()) {
            return ResultDTO.failure(HttpStatus.FORBIDDEN, "系统当前不能填报");
        }

        Optional<BonusItem> optional = bonusItemDao.findById(id);
        if (optional.isPresent()) {
            BonusItem item = optional.get();
            UserInfo info = currentService.getCurrentUser();
            UserType type = UserType.get(info.getType());
            if (UserType.STUDENT.equals(type) || UserType.CLASS_CADRES.equals(type)) {//访问者是学生(包括班干部)
                //只能删除自己的材料
                if (!Objects.equals(info.getId(), item.getApplicant())) {
                    return ResultDTO.failure(HttpStatus.FORBIDDEN, "不能删除非本人的材料");
                }
            }
            bonusItemDao.delete(item);
            return ResultDTO.success("删除成功");
        } else {
            return ResultDTO.failure(HttpStatus.BAD_REQUEST, "错误的id");
        }
    }

    public ResultDTO addFileById(String id, MultipartFile file) {
        if (!systemService.getState().getData().getOpen()) {
            return ResultDTO.failure(HttpStatus.FORBIDDEN, "系统当前不能填报");
        }

        if (Objects.isNull(file) || file.isEmpty()) {
            return ResultDTO.failure(HttpStatus.BAD_REQUEST, "未上传文件");
        }
        Optional<BonusItem> optional = bonusItemDao.findById(id);
        if (!optional.isPresent()) {
            return ResultDTO.failure(HttpStatus.BAD_REQUEST, "错误的id");
        }
        BonusItem item = optional.get();

        try {
            File pDict = new File(ConstValues.PROJECT_FILE_PATH_TEMP);
            if (!pDict.exists()) {
                pDict.mkdirs();
                LogUtil.log("目录创建 ———— {}", pDict.getCanonicalPath());
            }
            String tempSavePath = ConstValues.PROJECT_FILE_PATH_TEMP + "/" + System.currentTimeMillis() + ".temp";
            File temp = new File(tempSavePath);
            InputStream in = file.getInputStream();
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            FileCopyUtils.copy(buffer,temp);
            in.close();

            String objectName = item.getId() + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
            boolean success = fileService.upload(objectName, temp);
            temp.delete();
            if (!success) {
                throw new Exception("文件上传服务器遇到问题");
            }
            item.setFile(objectName);
            bonusItemDao.save(item);
        } catch (Exception e) {
            LogUtil.error(e.getMessage());
            throw new ImportException(e.getMessage());
        }

        return ResultDTO.success("上传成功", item);
    }
}
